package cn.memorynine.common.tool;

import cn.memorynine.common.config.JwtProperties;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author 黄睿曦
 */
@Component
public class JwtService {

    private JwtProperties jwtProperties;

    public JwtService(JwtProperties jwtProperties) {
            this.jwtProperties = jwtProperties;
        }

    public String createToken(String tokenData) throws UnsupportedEncodingException {
        return JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + this.jwtProperties.getTimeOut())).withIssuer(this.jwtProperties.getIssuer()).withSubject(tokenData).sign(Algorithm.HMAC256(this.jwtProperties.getSecretKey()));
    }

    public String getTokenData(String token) throws UnsupportedEncodingException {
        return JWT.require(Algorithm.HMAC256(this.jwtProperties.getSecretKey())).withIssuer(this.jwtProperties.getIssuer()).build().verify(token).getSubject();
    }

}
